#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include"Stack.h"
void Swap(int* p1, int* p2)
{
	int tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
void InsertSort(int* a, int size)
{
	for (int i = 0; i < size - 1; i++)
	{
		int end = i;
		int tmp = a[end + 1];
		while (end >= 0)
		{
			if (a[end] > tmp)
			{
				a[end + 1] = a[end--];
				a[end + 1] = tmp;
			}
			else
				break;
		}
		//a[end + 1] = tmp;
	}
}
int GetMidi(int* a, int left, int right)
{
	int Midi = (left + right) / 2;
	if (a[left] < a[Midi])
	{
		if (a[Midi] < a[right])
			return Midi;
		else if (a[left] < a[right])
			return right;
		else
			return left;
	}
	else //a[left] > a[Midi]
	{
		if (a[Midi] > a[right])
			return Midi;
		else if (a[left] > a[right])
			return right;
		else
			return left;
	}
}
int PartSort1(int* a, int left, int right)
{
	int midi = GetMidi(a, left, right);
	Swap(&a[left], a[midi]);
	int keyi = left;
	int begin = left, end = right;
	while (begin < end)
	{
		while (begin < end && a[end] >= a[keyi])
			end--;
		while (begin < end && a[begin] <= a[keyi])
			begin++;
		Swap(&a[end], &a[begin]);
	}
	Swap(&a[end], &a[keyi]);
	return end;
}
int PartSort2(int* a, int left, int right)
{
	int midi = GetMidi(a, left, right);
	Swap(&a[left], a[midi]);
	int keyi = left;
	int prev = keyi,cur = keyi + 1;
	while (cur <= right)
	{
		if (a[cur] < a[keyi] && ++prev != cur)
			Swap(&a[cur], &a[prev]);
		cur++;
	}
	Swap(&a[keyi], &a[prev]);
	return prev;
}
void QuickSort(int* a, int left, int right)
{
	if (left >= right)
		return;
	if ((right - left + 1) < 10)
	{
		InsertSort(a + left, right - left + 1);
	}
	else
	{
		int keyi = PartSort2(a, left, right);
		QuickSort(a, left, keyi - 1);
		QuickSort(a, keyi + 1, right);
	}
}
void QuickSortNonR(int* a, int left, int right)
{
	ST st;
	STInit(&st);
	STPush(&st, right);
	STPush(&st, left);
	while (!STEmpty(&st))
	{
		int begin = STTop(&st);
		STPop(&st);
		int end = STTop(&st);
		STPop(&st);
		int keyi = PartSort2(a, begin, end);
		if (keyi + 1 < end)
		{
			STPush(&st, end);
			STPush(&st, keyi + 1);
		}
		if (begin < keyi - 1)
		{
			STPush(&st, keyi - 1);
			STPush(&st, begin);
		}
	}
	STDesTroy(&st);
}
int main()
{
	int arr[] = { 1,8,7,6,5,4,3,2,9 };
	int size = sizeof(arr) / sizeof(arr[0]);
	//InsertSort(arr, size);
	//QuickSort(arr, 0, size - 1);
	QuickSortNonR(arr,0,size - 1);
	for (int i = 0; i < size; i++)
	{
		printf("%d", arr[i]);
	}
	return 0;
}